package com.mall.shopping.services;

import com.mall.shopping.ICartService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.converter.CartItemConverter;
import com.mall.shopping.dal.entitys.Item;
import com.mall.shopping.dal.persistence.ItemMapper;
import com.mall.shopping.dto.*;
import com.mall.shopping.services.cache.CacheManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.redisson.api.RScoredSortedSet;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author liXiaoFei
 * @date 2021/10/31 11:16
 */
@Service
public class CartServiceImpl implements ICartService {

    //商品的mapper
    @Autowired
    ItemMapper itemMapper;

    //缓存事务对象
    @Autowired
    CacheManager cacheManager;

    /**
     * 获取当前用户的购物车
     * @param request 用户id
     * @return 该用户的购物车结果
     */
    @Override
    public CartListByIdResponse getCartListById(CartListByIdRequest request) {
        CartListByIdResponse response = new CartListByIdResponse();
        try {
            request.requestCheck();
            //根据userId获取当前用户购物车Map
            Map<Long, CartProductDto> productDtoMap = getUserCarts(request.getUserId());

            //获取用户购物车添加商品时间记录
            RScoredSortedSet<Long> userAddCartTime = cacheManager.getUserAddCartTime(request.getUserId());
            Collection<Long> all;
            //取出来就是按照时间排序的集合
            if (userAddCartTime != null){
                all = userAddCartTime.readAll();
            }else {
                all = new ArrayList<>();
            }
            ArrayList<CartProductDto> cartProductDtos = new ArrayList<>();
            for (Long time : all) {
                //按照时间排序放进去
                cartProductDtos.add(productDtoMap.get(time));
            }
            //倒序
            Collections.reverse(cartProductDtos);

            response.setCartProductDtos(cartProductDtos);
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            response.setCode(ShoppingRetCode.DB_EXCEPTION.getCode());
            response.setMsg(ShoppingRetCode.DB_EXCEPTION.getMessage());
        }
        return response;
    }

    /**
     * 添加商品到购物车
     * @param request 用户id、要添加商品的id、添加购物车的商品数量
     * @return 添加结果
     */
    @Override
    public AddCartResponse addToCart(AddCartRequest request) {
        AddCartResponse response = new AddCartResponse();
        try {
            //根据userId获取当前用户购物车Map
            Map<Long, CartProductDto> userCarts = getUserCarts(request.getUserId());

            CartProductDto productDto = userCarts.get(request.getItemId());
            if (productDto != null){
                //不等于null,说明当前用户购物车中有该商品,需要进行合并
                if (productDto.getProductNum() + request.getNum() > productDto.getLimitNum()){
                    //如果加入购物车商品数量大于商品的限制购买数量，返回参数校验失败响应结果
                    response.setCode(ShoppingRetCode.PARAMETER_VALIDATION_FAILED.getCode());
                    response.setMsg(ShoppingRetCode.PARAMETER_VALIDATION_FAILED.getMessage());
                    return response;
                }
                //只需要添加数量即可
                productDto.setProductNum(productDto.getProductNum() + request.getNum());
            }else {//说明该商品在购物车中没有添加
                //查询商品信息
                Item item = itemMapper.selectByPrimaryKey(request.getItemId());
                //转换
                productDto = CartItemConverter.item2Dto(item);
                //添加当前用户购物车中商品数量
                productDto.setProductNum(request.getNum().longValue());
                //选中状态默认全部为false
                productDto.setChecked("false");
            }

            //将购物车商品对象放入购物车
            userCarts.put(request.getItemId(),productDto);

            //更新购物车
            updateCarts(userCarts,request.getUserId());

            //将添加记录放入该对象的添加商品时间记录
            RScoredSortedSet<Long> userAddCartTime = cacheManager.getUserAddCartTime(request.getUserId());
            //生成时间 202110311031类型
            double addTime = Double.parseDouble(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
            userAddCartTime.add(addTime,request.getItemId());

            //返回响应结果
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        }catch (Exception e){
            e.printStackTrace();
            response.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            response.setMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
        }
        return response;
    }


    /**
     * 修改购物车中商品的
     * @param request UpdateCartNumRequest
     * @return UpdateCartNumResponse
     */
    @Override
    public UpdateCartNumResponse updateCartNum(UpdateCartNumRequest request) {
        UpdateCartNumResponse response = new UpdateCartNumResponse();
        try {
            request.requestCheck();

            if (request.getNum() == 0){//数量等于0说明是删除该商品
                DeleteCartItemRequest deleteCartItemRequest = new DeleteCartItemRequest();
                deleteCartItemRequest.setUserId(request.getUserId());
                deleteCartItemRequest.setItemId(request.getItemId());
                deleteCartByUserIdAndItemId(deleteCartItemRequest);
            }else {
                //获得该用户的购物车Map
                Map<Long, CartProductDto> userCarts = getUserCarts(request.getUserId());
                //进行参数修改赋值
                CartProductDto cartProductDto = userCarts.get(request.getItemId());
                cartProductDto.setProductNum(Long.valueOf(request.getNum()));
                //选中状态从request中取出
                cartProductDto.setChecked(request.getChecked());
                //添加到个人的购物车Map
                userCarts.put(request.getItemId(),cartProductDto);
                //更新购物车
                updateCarts(userCarts, request.getUserId());
            }

            //返回响应结果
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            response.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            response.setMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
        }
        return response;
    }



    /**
     * 全选购物车的商品
     * @param request 用户id和是否选中
     * @return 结果
     */
    @Override
    public CheckAllItemResponse checkAllCartItem(CheckAllItemRequest request) {
        CheckAllItemResponse response = new CheckAllItemResponse();
        try {
            request.requestCheck();
            Map<Long, CartProductDto> userCarts = getUserCarts(request.getUserId());
            Collection<CartProductDto> productDtos = userCarts.values();
            //为全选状态
            for (CartProductDto productDto : productDtos) {
                productDto.setChecked(request.getChecked());
                userCarts.put(productDto.getProductId(),productDto);
            }

            //更新购物车
            updateCarts(userCarts,request.getUserId());
            //返回响应结果
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            response.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            response.setMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
        }
        return response;
    }

    /**
     * 删除购物车中的商品
     * @param request 用户的id和要删除的商品id
     * @return 结果
     */
    @Override
    public DeleteCartItemResponse deleteCartItem(DeleteCartItemRequest request) {
        DeleteCartItemResponse response = new DeleteCartItemResponse();
        try {
            //删除商品
            deleteCartByUserIdAndItemId(request);

            //返回响应结果
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            response.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            response.setMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
        }

        return response;
    }




    /**
     * 删除购物车中选中的商品
     * @param request userId
     * @return 删除结果
     * 该方法需要从购物车中的购物车商品对象的checked属性中取出是否为选中状态
     */
    @Override
    public DeleteCheckedItemResposne deleteCheckedItem(DeleteCheckedItemRequest request) {
        DeleteCheckedItemResposne response = new DeleteCheckedItemResposne();
        try {
            request.requestCheck();
            //获取当前用户的购物车
            Map<Long, CartProductDto> userCarts = getUserCarts(request.getUserId());
            //取出全部商品
            Collection<CartProductDto> userAllCartProduct = userCarts.values();
            //遍历商品
            for (CartProductDto cartProductDto : userAllCartProduct) {
                //如果选中状态为true,则进行删除
                if ("true".equals(cartProductDto.getChecked())){
                    deleteCartByUserIdAndItemId(new DeleteCartItemRequest(request.getUserId(),cartProductDto.getProductId()));
                }
            }

            //返回响应结果
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            response.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            response.setMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
        }

        return response;
    }

    /**
     * 清空购物车
     * @param request userId和商品的id的List
     * @return 清空结果
     */
    @Override
    public ClearCartItemResponse clearCartItemByUserID(ClearCartItemRequest request) {
        ClearCartItemResponse response = new ClearCartItemResponse();
        try {
            Map<Long, CartProductDto> userCarts = getUserCarts(request.getUserId());
            List<Long> productIds = request.getProductIds();
            for (Long productId : productIds) {
                deleteCartByUserIdAndItemId(new DeleteCartItemRequest(request.getUserId(),productId));
            }
            //更新购物车
            updateCarts(userCarts,request.getUserId());

            //返回响应结果
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            response.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            response.setMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
        }

        return response;
    }


    /**
     * 获取当前用户的购物车方法
     * @param userId 用户id
     * @return 当前用户购物车map
     */
    private Map<Long, CartProductDto> getUserCarts(Long userId) {
        //获取购物车Map
        Map<Long, Map<Long, CartProductDto>> carts = cacheManager.getCarts();
        //根据userId获取当前用户购物车Map
        Map<Long, CartProductDto> productDtoMap = carts.get(userId);
        if (productDtoMap == null){
            productDtoMap = new HashMap<>();
        }
        return productDtoMap;
    }

    /**
     * 更新购物车信息
     * @param userCarts 当前用户的购物车
     * @param userId 当前用户的id
     */
    private void updateCarts(Map<Long, CartProductDto> userCarts, Long userId) {
        Map<Long, Map<Long, CartProductDto>> carts = cacheManager.getCarts();
        carts.put(userId, userCarts);
    }

    /**
     * 删除商品
     * @param request 用户id、商品id
     * 该方法作用是为了复用
     */
    private void deleteCartByUserIdAndItemId(DeleteCartItemRequest request) {
        //删除当前用户购物车中该商品
        Map<Long, CartProductDto> userCarts = getUserCarts(request.getUserId());
        userCarts.remove(request.getItemId());

        //删除当前用户该商品排序的信息
        RScoredSortedSet<Long> userAddCartTime = cacheManager.getUserAddCartTime(request.getUserId());
        userAddCartTime.remove(request.getItemId());

        //更新购物车
        updateCarts(userCarts, request.getUserId());
    }

}
